from datetime import datetime
from typing import List, Union, Optional

from fastapi import APIRouter
from pydantic import BaseModel, Field, field_validator, ValidationError

app5 = APIRouter()

class Address(BaseModel):
    province: str
    city: str

class UserIn(BaseModel):
    name: str
    password: str
    age: int = Field(default=18,gt=0,lt=100)
    gender: str
    birthday: Union[str, datetime] = Field(default=datetime.today())
    firends: Optional[List[str]] = Field(default=[])
    address: Address

# 验证名字必须是字符
@field_validator('name')
@classmethod
def name_must_alpha(cls,value):
    if not value.isalpha():
        raise ValidationError('name必须是字符串')
    return value



class UserOut(BaseModel):
    name: str
    age: int
    gender: str


@app5.post('/data',response_model=UserOut)
async def data(user:UserIn):
    print(user,type(user))
    print(user.name,user.age,user.gender)
    # return {"user": user}
    return user